import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { PrismaClient, Prisma } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  // private readonly logger = new Logger(PrismaService.name);
  private readonly logger = new Logger('Prisma');

  constructor() {
    super({
      log: [
        {
          emit: 'event',
          level: 'query',
        },
      ],
    });
  }

  async onModuleInit() {
    await this.$connect();

    // 监听 Prisma 的查询事件，并使用显式类型
    const neverValue: never = 'query' as unknown as never;
    this.$on(neverValue, (event: Prisma.QueryEvent) => {
      this.logger.log(`Mapped {Query: ${event.query} } SQL`);
      this.logger.log(
        `Mapped {Params: ${event.params} ,Duration: ${event.duration}ms} Params`,
      );
    });
  }
}
